package com.suncaper.shop.service;

import com.suncaper.shop.component.Utils;
import com.suncaper.shop.domain.*;
import com.suncaper.shop.mapper.CommentMapper;
import com.suncaper.shop.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    private CommentExample commentExample;

    @Autowired
    private ProductMapper productMapper;

    private ProductExample productExample;

    private Utils utils = new Utils();

    public Boolean saveComment(Integer pid, Comment comment, HttpSession session) {

        if (session.getAttribute("userInfo") == null) {

            return false;
        }
        comment.setUid(((User) session.getAttribute("userInfo")).getId());
        comment.setUname(((User) session.getAttribute("userInfo")).getUsername());
        comment.setCommentId(utils.getCode());
        comment.setCdate(new Date());
        commentMapper.insert(comment);

        Integer star = 0;
        //得到该商品的总评论
        List<Comment> commentList = getComments(pid);
        for (Comment item : commentList) {
            star += item.getStar();
        }
        star = star / commentList.size();
        Product product = productMapper.selectByPrimaryKey(pid);
        product.setStar(star * 15);
        product.setReviews(commentList.size());
        productMapper.updateByPrimaryKey(product);
        return true;
    }

    /**
     * 根据pid获得该商品的评论信息
     *
     * @param pid
     * @return
     */
    public List<Comment> getComments(Integer pid) {
        commentExample = new CommentExample();
        commentExample.createCriteria().andPidEqualTo(pid);
        List<Comment> commentList = commentMapper.selectByExample(commentExample);
        return commentList;
    }
}
